package com.atguigu.springcloud.大批量任务处理.config;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author XiongJianLin
 * @date Created in 2025/2/10 14:17
 */
@Configuration
public class ThreadPoolConfig {
    @Resource
    private ThreadPoolProperties poolProperties;

    @Bean
    public ThreadPoolTaskExecutor threadPoolExecutorConfig() {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        threadPool.setCorePoolSize(poolProperties.getCorePoolSize());
        threadPool.setMaxPoolSize(poolProperties.getMaxPoolSize());
        threadPool.setQueueCapacity(poolProperties.getQueueCapacity());
        threadPool.setKeepAliveSeconds(poolProperties.getKeepAliveSeconds());
        threadPool.setThreadNamePrefix("spring默认线程池");
        // 线程池对拒绝任务（无线程可用）的策略
        threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 任务都完成再关闭线程池
        threadPool.setWaitForTasksToCompleteOnShutdown(true);
        // 任务初始化
        threadPool.initialize();
        return threadPool;
    }
}
